package yxy.game.pm2.command.union.boss;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionBossMessage;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;
import yxy.game.pm2.module.union.boss.UnionBossHandle;
import yxy.game.pm2.module.union.boss.UnionPlayerBoss;
import yxy.game.pm2.module.union.player.UnionPlayer;

/** 联盟BOSS 联盟BOSS扫荡 */
@MessageType(proto = Command.UnionBossSweep, classtype = UnionBossMessage.UnionBossSweepRequest.class)
public class CMD_UnionBossSweep extends Command<UnionBossMessage.UnionBossSweepRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionBossMessage.UnionBossSweepRequest request) {
		String playerCode = messageSource.getTag();

		UnionBossMessage.UnionBossSweepResponse.Builder response = UnionBossMessage.UnionBossSweepResponse.newBuilder();

		// 检查是否已经有联盟
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		Result result = new UnionHandle().checkPlayerUnion(entry);
		if (!result.equals(Result.UnionIn)) {
			send(messageSource, response, result);
			return;
		}
		RedisLock uLock = UnionBean.lock(entry.getUnionBean().getCode());
		RedisLock pLock = UnionPlayer.lock(entry.getPlayerCode());
		try {
			if (uLock.tryLock() && pLock.tryLock()) {

				UnionBean union = entry.reloadUnionBean();
				UnionPlayer unionPlayer = entry.reloadUnionPlayer();
				UnionPlayerBoss playerBoss = unionPlayer.getBoss();

				// 判断次数
				if (playerBoss.times() <= 0) {
					send(messageSource, response, Result.UnionBossTimesLack);// 你的挑战次数用完了
					return;
				}

				// 处理扫荡
				result = new UnionBossHandle().bossSweep(unionPlayer, union, response);
				send(messageSource, response, result);

				union.active();
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			uLock.unlock();
			pLock.unlock();
		}
	}

	private void send(MessageSource messageSource, UnionBossMessage.UnionBossSweepResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}